package com.avecsys.quotemanager.mbeans.system;

import java.io.Serializable;
import java.util.Map;

import javax.faces.context.FacesContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.avecsys.quotemanager.constants.ApplicationConstants;
import com.avecsys.quotemanager.dao.common.EnumActor;
import com.avecsys.quotemanager.dao.common.EnumTransactionStatus;
import com.avecsys.quotemanager.exception.BaseException;
import com.avecsys.quotemanager.exception.BusinessException;
import com.avecsys.quotemanager.exception.UserSessionNotFoundException;
import com.avecsys.quotemanager.mbeans.core.BaseMBean;
import com.avecsys.quotemanager.pojos.CompanyMasterPojo;
import com.avecsys.quotemanager.pojos.SystemUsersPojo;
import com.avecsys.quotemanager.service.common.CommonService;
import com.avecsys.quotemanager.service.system.SystemUserService;
import com.avecsys.quotemanager.service.user.UserMasterService;
import com.avecsys.quotemanager.utils.MessageBoardUtil;
import com.avecsys.quotemanager.utils.SystemConfig;
import com.avecsys.quotemanager.utils.TransactionStatus;

public class SystemUsersMBean extends BaseMBean implements Serializable {

	private final Log log = LogFactory.getLog(SystemUsersMBean.class);

	private SystemUserService systemUserService;

	private UserMasterService userMasterService;

	private CommonService commonService;

	private SystemUsersPojo systemUsersPojo = new SystemUsersPojo();

	private String selectedCompanyId;

	private String selectedSystemCompanyName;

	private String confirmPassword;

	private String existingEmailAddress;

	public String actionCancel() {
		try {
			FacesContext faceContext = FacesContext.getCurrentInstance();
			SystemUsersListMBean systemUsersListMBean = (SystemUsersListMBean) faceContext
					.getApplication().evaluateExpressionGet(faceContext,
							"#{systemUsersListMBean}",
							SystemUsersListMBean.class);
			systemUsersListMBean.loadAllUsers();
		} catch (BusinessException e) {
			log.error(e);
		}
		return "openListUsersForSystem";
	}

	/**
	 * Action Method to save system Information
	 * 
	 * @return Navigation Page
	 */
	public String actionSaveSystemUser() {
		try {
			log.info("Started Saving System User Information into database");
			// Step1: Update user modification information
			updateUserInformation(systemUsersPojo);
			// Step2: Get the systemPojo associate to the user
			CompanyMasterPojo companyMasterPojo = systemUserService.getCompanyMasterForSystem();
			systemUsersPojo.setCompanyMasterPojo(companyMasterPojo);
			// Mark Email Verified status as false if the email is different
			// from the current one
			if (getExistingEmailAddress() != null
					&& !getExistingEmailAddress().equalsIgnoreCase(
							systemUsersPojo.getUserMasterPojo().getEmail())) {
				systemUsersPojo.getUserMasterPojo().setEmailVerfied(
						Boolean.FALSE.toString());
			}
			TransactionStatus transactionStatus = userMasterService
					.saveSystemUser(systemUsersPojo);
			MessageBoardUtil.publishTransactionStatusMessage(transactionStatus,
					EnumActor.SYSTEM_USER, "messageBoardId", "",
					new Object[] { systemUsersPojo.getUserMasterPojo()
							.getUserName() });
			// Refresh the system users list
			FacesContext faceContext = FacesContext.getCurrentInstance();
			SystemUsersListMBean systemUsersListMBean = (SystemUsersListMBean) faceContext
					.getApplication().evaluateExpressionGet(faceContext,
							"#{systemUsersListMBean}",
							SystemUsersListMBean.class);
			systemUsersListMBean.loadAllUsers();
			// Send Verification Email
			if (transactionStatus.getStatus().intValue() == EnumTransactionStatus.SAVE_SUCESS
					.ordinal()) {
				log.info("Sending Activate Email Notification to System User");
				commonService.sendEmail(systemUsersPojo);
			} else if (transactionStatus.getStatus().intValue() == EnumTransactionStatus.UPDATE_SUCCESS
					.ordinal()) {
				// Send Notification only if user changed existing email address
				if (!getExistingEmailAddress().equalsIgnoreCase(
						systemUsersPojo.getUserMasterPojo().getEmail())) {
					log.info("Sending Activate Email Notification to System User");
					commonService.sendEmail(systemUsersPojo);
				}
			}
			log.info("Completed saving System User Information into database sucessfully");
		} catch (BaseException e) {
			log.error(e);
			MessageBoardUtil.publishException(e);
		}
		return "openListUsersForSystem";
	}

	public CommonService getCommonService() {
		return commonService;
	}

	/**
	 * @return the confirmPassword
	 */
	public String getConfirmPassword() {
		return confirmPassword;
	}

	public String getExistingEmailAddress() {
		return existingEmailAddress;
	}

	/**
	 * @return the selectedSystemCompanyName
	 */
	public String getSelectedSystemCompanyName() {
		return selectedSystemCompanyName;
	}

	/**
	 * @return the selectedCompanyId
	 */
	public String getSelectedCompanyId() {
		return selectedCompanyId;
	}

	/**
	 * @return the systemMasterService
	 */
	public SystemUserService getSystemUserService() {
		return systemUserService;
	}

	public SystemUsersPojo getSystemUsersPojo() {
		return systemUsersPojo;
	}

	/**
	 * @return the userMasterService
	 */
	public UserMasterService getUserMasterService() {
		return userMasterService;
	}

	public void setCommonService(CommonService commonService) {
		this.commonService = commonService;
	}

	/**
	 * @param confirmPassword
	 *            the confirmPassword to set
	 */
	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	public void setExistingEmailAddress(String existingEmailAddress) {
		this.existingEmailAddress = existingEmailAddress;
	}

	/**
	 * @param selectedSystemCompanyName
	 *            the selectedSystemCompanyName to set
	 */
	public void setSelectedSystemCompanyName(
			String selectedSystemCompanyName) {
		this.selectedSystemCompanyName = selectedSystemCompanyName;
	}

	/**
	 * @param selectedCompanyId
	 *            the selectedCompanyId to set
	 */
	public void setSelectedCompanyId(String selectedCompanyId) {
		this.selectedCompanyId = selectedCompanyId;
	}

	/**
	 * @param systemUserService
	 *            the systemUserService to set
	 */
	public void setSystemUserService(
			SystemUserService systemUserService) {
		this.systemUserService = systemUserService;
	}

	public void setSystemUsersPojo(SystemUsersPojo systemUsersPojo) {
		this.systemUsersPojo = systemUsersPojo;
	}

	/**
	 * @param userMasterService
	 *            the userMasterService to set
	 */
	public void setUserMasterService(UserMasterService userMasterService) {
		this.userMasterService = userMasterService;
	}

	/**
	 * Method to update the user information
	 * 
	 * @param systemUsersPojo
	 * @throws UserSessionNotFoundException
	 */
	public void updateUserInformation(SystemUsersPojo systemUsersPojo)
			throws UserSessionNotFoundException {
		// Update User Information to System
		super.updateUserInformation(systemUsersPojo, null);
		// Update User Information to Company
		super.updateUserInformation(systemUsersPojo.getUserMasterPojo(),
				systemUsersPojo.getModifiedDttm());
	}
}
